using System.Collections.Generic;
using UnityEngine;
using System.Collections;
using System.Linq;

public class LuckWheel : MonoBehaviour {

    private const int itemCount = 6;
    public float rotationSpeed = 720;
    public float rotationTime = 5;
    private float damping = 1;
    public GameObject[] itemPrefab;

    private List<GameObject> items = new List<GameObject>();
	// Use this for initialization
	void Start ()
	{
	    damping = rotationSpeed/rotationTime;
	    Reset();
	}

    private void Reset()
    {
        items.ForEach(o => Destroy(o));
        items.Clear();

        Vector3 size = this.renderer.bounds.size;
        float radiu = Mathf.Max(size.x, size.z)*0.5f;

        List<GameObject> tmp = new List<GameObject>(itemPrefab);
        for (int i = 0; i < itemCount; i++)
        {
            int index = Random.Range(0, tmp.Count);
            var go = Instantiate(tmp[index]) as GameObject;
            items.Add(go);

            float angle = (float) 360/itemCount*i;
            //Debug.Log(angle);
            Vector3 dir = (Quaternion.AngleAxis(angle, this.transform.up)*this.transform.right).normalized;
            Vector3 pos = dir*radiu;
            //Debug.Log(pos);

            go.transform.position = this.transform.position + pos;
            go.transform.up = dir;
            go.transform.parent = this.transform;
        }
    }

    private float speed;
    //private float rotation;
    public void Go()
    {
        speed = rotationSpeed;
    }

    // Update is called once per frame
	void Update () {
	    if (speed>0)
	    {
	        float rotation = Time.deltaTime*speed;
            //Debug.Log(speed);
            this.transform.rotation *= Quaternion.AngleAxis(rotation, Vector3.up);
	        //rotation += Time.deltaTime*speed;
	        speed -= Time.deltaTime*damping;
	    }
	}
}
